package com.isky.visual.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.isky.visual.constant.CommonConstant;
import com.isky.visual.exception.GlobalException;
import com.isky.visual.proj.service.IPanelGroupService;
import com.isky.visual.result.CodeMsg;
import com.isky.visual.result.ResultVo;
import com.isky.visual.user.entity.User;
import com.isky.visual.user.entity.UserGroup;
import com.isky.visual.user.entity.UserGroupUser;
import com.isky.visual.user.mapper.UserGroupMapper;
import com.isky.visual.user.mapper.UserGroupUserMapper;
import com.isky.visual.user.mapper.UserMapper;
import com.isky.visual.user.service.IuserService;
import com.isky.visual.user.vo.LoginVo;
import com.isky.visual.user.vo.UnifiedVisualResult;
import com.isky.visual.user.vo.UserInfoTreeVO;
import com.isky.visual.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Wrapper;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author wudl
 * @since 2020-04-15
 */
@Service
public class UserServiceImpl implements IuserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserGroupMapper userGroupMapper;

    @Autowired
    UserGroupUserMapper userGroupUserMapper;

    @Autowired
    IPanelGroupService iPanelGroupService;

    @Autowired
    TransactionTemplate transactionTemplate;

    /**
     * 获取所有的用户
     *
     * @return
     */
    @Override
    public ResultVo<List<User>> getUser() {
        List<User> users = userMapper.selectList(null);
        return ResultVo.success(users);
    }

    @Override
    public ResultVo<String> login(LoginVo loginVo) {

        if (loginVo == null) {
           return  ResultVo.error(CodeMsg.USERNAME_NULL.getMsg());
        }
        String username = loginVo.getUsername();
        String password = loginVo.getPassword();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);
        if (user==null) {
            return  ResultVo.error(CodeMsg.USERNAME_NULL);
        }
        Map map = new HashMap(16);
        map.put("password", user.getPassword());
        if (checkLogin(map, password)) {

            return ResultVo.success(CodeMsg.LOGIN_SUCCESS.getMsg());
        } else {
            return ResultVo.error(CodeMsg.PASSWORD_ERROR.getMsg());
        }
    }

    private boolean checkLogin(Map<String, Object> userMap, String password) {

        if (MD5Util.verify(password, userMap.get("password").toString())) {
            return true;
        }
        return false;
    }

    @Override
    public boolean checkLogin(User user , String password){
//        Map map = new HashMap(16);
//        map.put("password", user.getPassword());
//       return  checkLogin(map, password);
        return Objects.equals(user.getPassword(),password);
    }

    @Override
    public List<UserInfoTreeVO> groupTreeInfo() {
        return userMapper.groupTreeInfo();
    }

    @Override
    public boolean deleteGroup(Long groupId) {
        Boolean execute = transactionTemplate.execute(transactionStatus -> {

            userGroupMapper.deleteById(groupId);

            QueryWrapper<UserGroupUser> queryWrapper = new QueryWrapper<>();
            UserGroupUser userGroupUser = new UserGroupUser();
            userGroupUser.setGroupId(groupId);
            queryWrapper.setEntity(userGroupUser);

            userGroupUserMapper.delete(queryWrapper);
            return true;
        });

        return execute;
    }

    @Override
    public User query(Long userId) {
        return userMapper.selectById(userId);
    }

    @Override
    public User query(String userName) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        User queryObject = new User();
        queryObject.setUsername(userName);
        queryWrapper.setEntity(queryObject);

        return userMapper.selectOne(queryWrapper);
    }

    /**
     * 把用户信息补充到本地数据库
     * @param unifiedVisual
     * @return
     */
    @Override
    public User supplement(UnifiedVisualResult unifiedVisual) {
        Long groupId = unifiedVisual.getId();
        String groupName = unifiedVisual.getGroupName();
        String username = unifiedVisual.getUsername();
        Long userId = unifiedVisual.getUid();

        User user = this.query(userId);

        User finalUser = user;
        transactionTemplate.execute(transactionStatus -> {
            if(finalUser == null){
                User userNew =new User();
                userNew.setId(userId);
                userNew.setUsername(username);
                userNew.setName(username);
                userMapper.insert(userNew);

                //新增2个仪表盘root组
                iPanelGroupService.addRootByUserId(userId);
            }

            // 用户组存在则更新，不存在则新增
            UserGroup userGroupOld = userGroupMapper.selectById(groupId);
            if(userGroupOld == null){
                UserGroup userGroup = new UserGroup();
                userGroup.setId(groupId);
                userGroup.setGroupName(groupName);
                userGroup.setValid(true);
                userGroupMapper.insert(userGroup);

                UserGroupUser userGroupUser = new UserGroupUser();
                userGroupUser.setGroupId(groupId);
                userGroupUser.setUserId(userId);
                userGroupUser.setValid(true);
                userGroupUserMapper.insert(userGroupUser);
            }else{
                userGroupOld.setGroupName(groupName);
                userGroupOld.setValid(true);
                userGroupMapper.updateById(userGroupOld);
            }
            return true;
        });

        if(user == null) {
            user = this.query(userId);
        }

        return user;
    }
}
